from rest_framework.response import Response
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
from admins.models import Admins


class APIResponse(Response):
    def __init__(self, code=200, msg='ok', http_status=None, headers=None, exception=False, new_token_admin=None,
                 **kwargs):
        data = {
            'code': code,
            'msg': msg,
        }
        if new_token_admin:
            new_token = self._get_new_token(new_token_admin)
            data.update({'new_token': new_token})
        if kwargs:
            data.update(kwargs)
        super().__init__(data=data, status=http_status, headers=headers, exception=exception)

    def _get_new_token(self, admin_user):
        temp_admin = Admins(id=admin_user['id'], username=admin_user['username'])
        payload = jwt_payload_handler(temp_admin)
        new_token = jwt_encode_handler(payload)
        return new_token
